<?php

namespace app\admin\model\weixin;

use think\Model;

class Reply extends Model
{

    // 表名
    protected $name = 'weixin_reply';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'reply_type_text',
        'status_text'
    ];

    public function getReplyTypeList()
    {
        return ['text' => __('Reply_type text'), 'image' => __('Reply_type image'), 'news' => __('Reply_type news'), 'voice' => __('Reply_type voice'), 'video' => __('Reply_type video')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }

    public function getReplyTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['reply_type']) ? $data['reply_type'] : '');
        $list = $this->getReplyTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected static function init()
    {
        //写入前
        self::beforeWrite(function($row){
            if (isset($row->event_type) && $row->event_type == 'default') {
                $row->keyword = 'default';
            } else if (isset($row->event_type) && $row->event_type == 'subscribe') {
                $row->keyword = 'subscribe';
            }
            if (isset($row->event_type) && in_array($row->reply_type, ['image', 'voice', 'video'])) {
                $content = $row->content;
                if ($row->reply_type == 'image') {
                    $data = $_SERVER['DOCUMENT_ROOT'] . $content['image'];
                }
                if ($row->reply_type == 'voice') {
                    $data = $_SERVER['DOCUMENT_ROOT'] . $content['voice'];
                }
                if ($row->reply_type == 'video') {
                    $data = [];
                    $data['title'] = $content['video_title'];
                    $data['description'] = $content['video_description'];
                    $data['file'] = $_SERVER['DOCUMENT_ROOT'] . $content['video'];
                }
                //上传资源
                if(!isset($content[$row->reply_type . '_media_id']) || !$content[$row->reply_type . '_media_id']) {
                    $content[$row->reply_type . '_media_id'] = \addons\weixin\library\Event::material($row->reply_type, $data);
                }
                $row->content = $content;
            }
            $row->content = is_array($row->content) ? json_encode($row->content) : '';
        });
    }
}